import store from "./store"
import { router, addRoutes } from "./router"
import { getToken } from "~/composables/auth"
import { toast, showFullLoading, hideFullLoading } from "~/composables/util"

// 全局前置守卫拦截
// 设置该boolean值是为了优化getinfo获取信息避免前端重复调用getinfo方法
let hasGetInfo = false

router.beforeEach(async (to, from, next) => {

	// 显示loading
	showFullLoading()

	// to: 代表即将到达的路径  from: 代表从哪个路径来
	const token = getToken()

	// 判断用户是否登录并做出相应提示
	if (!token && to.path != "/login") {
		// 未登录的错误提示
		toast("请先登录您的账号", "warning")
		// 未登录强制跳转登录页
		return next({ path: "/login" })
	}

	// 防止用户重复登录
	if (token && to.path == "/login") {
		toast("请勿重复登录", "warning")
		return next({ path: from.path ? from.path : "/" })
	}

	// 如果用户已登录，则自动获取用户相关信息，并存储在vuex中
	let hasNewRoutes = false
	if (token && !hasGetInfo) {
		// 异步操作
		let { menus } = await store.dispatch("getinfo")
		// 加载getinfo后设置其值为true
		hasGetInfo = true
		// 动态添加路由
		hasNewRoutes =  addRoutes(menus)
	}

	// 设置页面标题
	let title = (to.meta.title ? to.meta.title : "") + "—black学长商城后台"
	document.title = title

	hasNewRoutes ? next	(to.fullPath) : next()

})

// 关闭全局loading
router.afterEach((to, from) => hideFullLoading())
